package middlewares

import (
	"net/http"
	"os"

	"go.uber.org/zap"
)

type Middleware func(http.Handler) http.Handler

type loggingResponseWriter struct {
	http.ResponseWriter
	statusCode int
}

func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
	return &loggingResponseWriter{w, http.StatusOK}
}

func (lrw *loggingResponseWriter) WriteHeader(code int) {
	lrw.statusCode = code
	lrw.ResponseWriter.WriteHeader(code)
}

func WithLog(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		lrw := NewLoggingResponseWriter(writer)

		handler.ServeHTTP(writer, request)
		zap.S().Infof("%s, request from : %s, status code : %d", request.RequestURI, request.RemoteAddr, lrw.statusCode)
	})
}

func WithEnvVersion(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		writer.Header().Set("VERSION", os.Getenv("VERSION"))
		handler.ServeHTTP(writer, request)
	})
}

func WithCloneReqHeaders(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		for s, values := range request.Header {
			for _, value := range values {
				writer.Header().Set(s, value)
			}
		}
		handler.ServeHTTP(writer, request)
	})
}
